import axios from "axios"
import Element from "element-ui"
import router from "@/router"
import store from "@/store";

// const baseUrl = 'http://203.56.183.189:80/api'
const baseUrl = 'http://127.0.0.1:8888/'
let permissionFlag = false
export function request(config){
    //创建axios实例
    const instance = axios.create({
        baseURL: baseUrl,
        timeout: 5000,
        headers: {
            'Content-Type':'application/json;charset=utf-8'
        },
        withCredentials: true,
    })
    //axios的拦截器  对发送和接收的请求进行拦截处理 处理token
    // 请求拦截
    instance.interceptors.request.use(resquest=>{
        resquest.headers['authorization'] = localStorage.getItem('token')//请求头赋值
        return resquest;//对拦截的请求放行
    })
    //响应拦截
    instance.interceptors.response.use(response=>{
        let res = response.data
        if (res.code === 200){
            return  response;
        }
        else if (res.code === 400) {
            if (res.message)
                Element.Message.error(res.message)
            else
                Element.Message.error('服务器错误 ~0.0~ ')
            return Promise.reject()
        }
        else if (res.code === 401) {//权限异常
            Element.Message.error('权限异常 -> '+response.data.message)
            store.dispatch('logout').then(() => {
                router.push("/").then(r => {})
                return Promise.reject('权限异常')
            })//退出登录
        }
        return  response;
    },error => {
        Element.Message.error('服务器错误 ~0.0~ ')
        return Promise.reject()
    })
    return instance(config);
}

export function baseWsIP(suffix,userId){
    return baseUrl.replace('http','ws') + '/' + suffix + '/' + userId
}